﻿using UnityEngine;
namespace GX
{

    public static class GxTools
    {
        static public T FindComponent<T>(this GameObject root, string name = null, bool isRecursively = false, bool includeDeactive = false) where T : Component
        {
            var go = root.FindGameObject(name, isRecursively, includeDeactive);
            if (null == go)
                return null;
            T t = go.GetComponent<T>();
            return t;
        }

        static public GameObject FindGameObject(this GameObject root, string name, bool isRecursively = false, bool includeDeactive = false)
        {
            if (string.IsNullOrEmpty(name))
                return root;
            if (includeDeactive || name.Contains("/"))
            {
                var child = root.transform.Find(name);
                return null == child ? null : child.gameObject;
            }
            else
            {
                var go = root.FindGameObjectByName(name, isRecursively, includeDeactive);
                return go;
            }
        }
        static GameObject FindGameObjectByName(this GameObject root, string name, bool isRecursively = false, bool includeDeactive = false)
        {
            Transform t = root.transform;
            int numChild = t.childCount;
            for (int i = 0; i < numChild; ++i)
            {
                var node = t.GetChild(i);
                if (includeDeactive || t.gameObject.activeSelf)
                {
                    if (node.name.Equals(name))
                        return node.gameObject;
                }
            }
            if (isRecursively)
            {
                for (int i = 0; i < numChild; ++i)
                {
                    var node = t.GetChild(i);
                    var ret = node.gameObject.FindGameObjectByName(name, isRecursively, includeDeactive);
                    if (null != ret)
                        return ret;
                }
            }
            return null;
        }
    }
}